package com.sywb.chuangyebao.contract;

import android.app.Activity;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.Comment;
import com.sywb.chuangyebao.bean.NewsOwner;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.utils.Utils;
import com.sywb.chuangyebao.view.dialog.CommentReplyDialog;
import com.sywb.chuangyebao.widget.RichTextView;

import org.bining.footstone.adapter.BaseRecyclerAdapter;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.TimeUtils;

import java.util.List;

public interface BaseNewsDetailContract {

    interface BaseView extends BaseRefreshContract.View {
        int getDialogViewHeight();

        void changeCommentCount(int count);

        void setIsFavorite(boolean isFavorite);
    }

    abstract class BasePresenter<T extends BaseView> extends BaseRefreshContract.Presenter<T> {

        protected CommentAdapter recyclerAdapter;

        protected String topicType;
        protected int topicId;
        protected int pageNumber = 1;

        public String getTopicType() {
            return topicType;
        }

        @Override
        public void onStart() {
            super.onStart();
            recyclerAdapter = new CommentAdapter(mActivity, mView);
            recyclerAdapter.setEmptyView(R.layout.layout_news_no_comment, true);
            setRecyclerAdapter(recyclerAdapter);
        }

        @Override
        public void onRecyclerItemLongClick(View view, int postion) {
            super.onRecyclerItemLongClick(view, postion);
//            Comment comment = recyclerAdapter.getItem(postion - 1);
//            if (String.valueOf(comment.from_uid).equals(SharedUtils.getString(Constants.USEROPENID))) {
//                delComment(comment.comment_id);
//            }
        }

        @Override
        public void onRecyclerItemChildClick(View view, int postion) {
            super.onRecyclerItemChildClick(view, postion);
            Comment comment = recyclerAdapter.getItem(postion - 1);
            switch (view.getId()) {
                case R.id.iv_head:
                case R.id.tv_name:
//                    mView.advance(UserIndexActivity.class, comment.from_uid);
                    Utils.goUserIndex(mView, comment.from_uid);
                    break;
                case R.id.tv_reply:
                    CommentReplyDialog dialogFragment = CommentReplyDialog.newInstance(mView.getDialogViewHeight(), JSON.toJSONString(comment), postion - 1, topicType);
                    dialogFragment.show(mView.getMyFragmentManager(), topicType);
                    break;
                case R.id.tv_zan_count:
                case R.id.iv_zan:
                    agree(Constants.TOPIC_TYPE_COMMENT, comment.comment_id, !comment.is_thumb, postion);
                    break;
                case R.id.tv_consult:
                    goConsult(comment.changtantong.project_id, comment.changtantong.company_id, Constants.COOKIE_PROJECT);
                    break;
            }
        }

        @Override
        public void onStartRefresh() {
            pageNumber = 1;
            getCommentList();
        }

        @Override
        public void onStartLoadMore() {
            pageNumber++;
            getCommentList();
        }

        public void getCommentList() {
            HttpUtils.listComment(topicType, topicId, pageNumber, new HttpCallback<List<Comment>>() {

                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onSuccess(List<Comment> comments) {
                    if (pageNumber == 1) {
                        recyclerAdapter.setTopicType(topicType);
                        recyclerAdapter.clearDatas();
                    }
                    if (comments != null && comments.size() == Constants.PAGESIZE) {
                        recyclerAdapter.setFooterView(null);
                    } else {
                        recyclerAdapter.setFooterView(R.layout.layout_footer);
                    }
                    recyclerAdapter.notifyDataChangedAfterLoadMore(comments);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    if (pageNumber > 1) {
                        onEndLoadMore();
                    }
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                    onEndRefresh();
                    isNoData();
                    if (recyclerAdapter.getDataCount() == 0) {
                        recyclerAdapter.setFooterView(null);
                        recyclerAdapter.notifyDataSetChanged();
                    }
                }
            });
        }

        /**
         * 点赞/取消点赞
         */
        public void agree(String topicType, int parentId, boolean isAgree, int postion) {
            if (!Utils.checkIsLogin()) {
                return;
            }
            HttpUtils.agree(topicType, parentId, isAgree, new HttpCallback<Object>(postion) {

                @Override
                public void onStart() {
                    super.onStart();
                    onStartAsync();
                }

                @Override
                public void onSuccess(Object o) {
                    int postion = (int) data;
                    if (postion >= 0) {
                        Comment comment = recyclerAdapter.getItem(postion - 1);
                        comment.is_thumb = !comment.is_thumb;
                        comment.thumb_count = comment.is_thumb ? comment.thumb_count + 1 : comment.thumb_count - 1;
                        recyclerAdapter.notifyDataSetChanged();
                    } else {
                        changeAgree();
                    }
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }

        /**
         * 收藏/取消收藏
         *
         * @param isAgree
         */
        public void favorite(boolean isAgree) {
            if (!Utils.checkIsNext(mView.getMyFragmentManager())) {
                return;
            }
            HttpUtils.favorite(topicType, topicId, isAgree, new HttpCallback<Object>(topicId) {

                @Override
                public void onStart() {
                    super.onStart();
                    onStartAsync();
                }

                @Override
                public void onSuccess(Object integer) {
                    changeFavorite();
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }

        /**
         * 关注/取消关注
         *
         * @param targetId 被关注对象id
         * @param isFollow 关注or取消关注（1：关注 ，0：取消）
         */
        public void follow(int targetId, boolean isFollow) {
            if (!Utils.checkIsLogin()) {
                return;
            }
            HttpUtils.follow(targetId, Constants.TOPIC_TYPE_USER, isFollow, new HttpCallback<Object>(topicId) {
                @Override
                public void onStart() {
                    super.onStart();
                    onStartAsync();
                }

                @Override
                public void onSuccess(Object data) {
                    changeFollow();
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }

        /**
         * 添加评论
         *
         * @param content 评论内容
         */
        public void addComment(String content) {
            if (!Utils.checkIsNext(mView.getMyFragmentManager())) {
                return;
            }
            HttpUtils.addComment(topicType, topicId, content, new HttpCallback<Object>() {

                @Override
                public void onStart() {
                    super.onStart();
                    onStartAsync();
                }

                @Override
                public void onSuccess(Object data) {
                    onStartRefresh();
                    RxBus.get().post(Constants.COMMENT_REPLY_CHANGE, "");
                    changeComment(true);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }

        /**
         * 删除评论
         *
         * @param commentId 评论ID
         */
        public void delComment(int commentId) {
            if (!Utils.checkIsLogin()) {
                return;
            }
            HttpUtils.delComment(commentId, new HttpCallback<String>() {

                @Override
                public void onStart() {
                    super.onStart();
                    onStartAsync();
                }

                @Override
                public void onSuccess(String data) {
                    onStartRefresh();
                    changeComment(false);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }

        public void goConsult(int projectid, int custid, String cookie) {
//            HttpUtils.getCode(projectid, custid, new HttpCallback<String>() {
//
//                @Override
//                public void onStart() {
//                    super.onStart();
//                    onStartAsync();
//                }
//
//                @Override
//                public void onSuccess(String s) {
//                    if (TextUtils.isEmpty(s)) {
//                        return;
//                    }
//                    mView.advance(WebActivity.class, "畅谈通", s);
//                }
//
//                @Override
//                public void onError(String strMsg) {
//                    super.onError(strMsg);
//                    showMessage(strMsg);
//                }
//
//                @Override
//                public void onFinish() {
//                    super.onFinish();
//                    onFinishAsync();
//                }
//
//            });

            Utils.goConsult(this, mView, projectid, custid, cookie);
        }

        /**
         * 滚动视图到顶部
         */
        public void goViewTop() {
            RecyclerView.LayoutManager layoutManager = commonRecycler.getLayoutManager();
            if (layoutManager instanceof LinearLayoutManager) {
                LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                int firstPosition = linearManager.findFirstVisibleItemPosition();
                int last = linearManager.findLastVisibleItemPosition();

                if (commonRecycler.getAdapter().getItemCount() > 1) {
                    linearManager.scrollToPositionWithOffset(1, 0);
                    linearManager.setStackFromEnd(true);
                }

//                if (firstPosition == 0 && last == 0) {
//                    //处于头部，滚动到第一个条目
//                    commonRecycler.scrollToPosition(1);
//                } else {
//                    //不是头部，滚动到头部
//                    commonRecycler.scrollToPosition(0);
//                }

            }
        }

        abstract void changeFollow();

        abstract void changeAgree();

        abstract void changeFavorite();

        abstract void changeComment(boolean isAdd);

        @Override
        public boolean useRecyclerDivider() {
            return false;
        }

    }

    class CommentAdapter extends BaseRecyclerAdapter<Comment> {

        private Activity mActivity;
        private BaseView mView;

        private String topicType;

        public CommentAdapter(Activity activity, BaseView mView) {
            super(activity, R.layout.item_answer_reply);
            this.mActivity = activity;
            this.mView = mView;
        }

        public void setTopicType(String topicType) {
            this.topicType = topicType;
        }

        @Override
        protected void setItemData(ViewHolderHelper viewHolderHelper, int i, Comment model) {
            if (model == null) {
                return;
            }

            viewHolderHelper.setItemChildClickListener(R.id.iv_head);
            viewHolderHelper.setItemChildClickListener(R.id.iv_user_type);
            viewHolderHelper.setItemChildClickListener(R.id.tv_name);
            viewHolderHelper.setItemChildClickListener(R.id.iv_zan);
            viewHolderHelper.setItemChildClickListener(R.id.tv_zan_count);
            viewHolderHelper.setItemChildClickListener(R.id.tv_consult);
            viewHolderHelper.setItemChildClickListener(R.id.tv_reply);

            NewsOwner commentUser = model.from_user;
            if (commentUser != null) {
                ImageView imageView = viewHolderHelper.getView(R.id.iv_head);
                GlideUtils.getCircleImageToUrl(mActivity, commentUser.getShowAvatar(), imageView);

                int userRole = commentUser.getUserRole();
                if (userRole == Constants.USER_TYPE_NORMAL) {
                    viewHolderHelper.setVisibility(R.id.iv_user_type, android.view.View.GONE);
                } else {
                    viewHolderHelper.setVisibility(R.id.iv_user_type, android.view.View.VISIBLE);
                    switch (userRole) {
                        case Constants.USER_TYPE_V:
                            viewHolderHelper.setImageResource(R.id.iv_user_type, R.drawable.official_icon);
                            break;
                        case Constants.USER_TYPE_PROJECT:
                            viewHolderHelper.setImageResource(R.id.iv_user_type, R.drawable.icon_project);
                            break;
                        case Constants.USER_TYPE_SERVICE:
                            viewHolderHelper.setImageResource(R.id.iv_user_type, R.drawable.icon_service);
                            break;
                        case Constants.USER_TYPE_TUTOR:
                            viewHolderHelper.setImageResource(R.id.iv_user_type, R.drawable.icon_teacher);
                            break;
                    }
                }

                viewHolderHelper.setText(R.id.tv_name, commentUser.getShowName());
            }

            if (model.changtantong == null) {
                viewHolderHelper.setVisibility(true, R.id.iv_zan, R.id.tv_zan_count, R.id.tv_time, R.id.tv_reply);
                viewHolderHelper.setVisibility(false, R.id.tv_consult);

                //是否赞
                viewHolderHelper.setImageResource(R.id.iv_zan, model.is_thumb ? R.drawable.praise_red : R.drawable.praise);
                viewHolderHelper.setTextColorRes(R.id.tv_zan_count, model.is_thumb ? R.color.messageRed : R.color.colorGray);
                viewHolderHelper.setText(R.id.tv_zan_count, model.getThumbCount());

                viewHolderHelper.setText(R.id.tv_time, TimeUtils.transformDate10(model.date_time));

                //回复个数
                TextView tvReply = viewHolderHelper.getView(R.id.tv_reply);
                int verticalPadding = (int) mContext.getResources().getDimension(R.dimen.dp_4);
                int horizontalPadding = (int) mContext.getResources().getDimension(R.dimen.dp_12);
                if (model.reply_count > 0) {
                    tvReply.setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding);
                    tvReply.setBackgroundResource(R.drawable.shape_detail_comment);
                } else {
                    tvReply.setPadding(0, verticalPadding, 0, verticalPadding);
                    tvReply.setBackgroundColor(Color.TRANSPARENT);
                }
                tvReply.setText(model.getReplyCount());

            } else {
                viewHolderHelper.setVisibility(false, R.id.iv_zan, R.id.tv_zan_count, R.id.tv_time, R.id.tv_point, R.id.tv_reply);
                viewHolderHelper.setVisibility(true, R.id.tv_consult);

                viewHolderHelper.setText(R.id.tv_consult, model.changtantong.btn_txt);
            }

            RichTextView tvComment = viewHolderHelper.getView(R.id.tv_comment);
            tvComment.setDataPostion(i);
            tvComment.setExpandView(true);
            tvComment.setExpandedOpen(false);
            tvComment.setDeviationDP(R.dimen.dp_88);
            tvComment.setOnLinkClickListener(new RichTextView.OnLinkClickListener() {
                @Override
                public void onAtClick(RichTextView richTextView, Object userId) {
                }

                @Override
                public void onTopicClick(RichTextView richTextView, Object topicId) {
                }

                @Override
                public void onEmojiClick(RichTextView richTextView, Object emoji) {
                }

                @Override
                public void onUrlClick(RichTextView richTextView, Object url) {
                }

                @Override
                public void onAllClick(RichTextView richTextView) {
                    int postion = richTextView.getDataPostion() - 1;
                    Comment comment = getItem(postion);
                    CommentReplyDialog dialogFragment = CommentReplyDialog.newInstance(mView.getDialogViewHeight(), JSON.toJSONString(comment), postion, topicType);
                    dialogFragment.show(mView.getMyFragmentManager(), topicType);
                }
            });
            tvComment.setText(model.content);

        }
    }
}

